using System.Buffers;
using SuperSocket.ProtoBase;

namespace Core;

public sealed class PlayPacketEncode : IPackageEncoder<BaseCommand>
{
    private const int HeaderSize = 3;

    public readonly static Dictionary<Type, CommandType> Commands = BaseCommand.Commands.ToDictionary(keySelector => keySelector.Value, comparer => comparer.Key);

    public int Encode(IBufferWriter<byte> writer, BaseCommand pack)
    {
        if (Commands.TryGetValue(pack.GetType(), out var command))
            throw new KeyNotFoundException(nameof(pack));

        var body = pack.EncodeBody();

        writer.WriteByteBigEndian((byte)command);
        writer.WriteInt16LittleEndian((short)body.Length); // body 的长度
        writer.Write(body); // 内容

        return HeaderSize + body.Length;
    }
}